package drds.configuration.mvc.upload;

import com.oreilly.servlet.multipart.FileRenamePolicy;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;

public class SimpleCosFileRenamePolicy implements FileRenamePolicy {

    /**
     * 文件名后缀
     */
    public static String getFiletype(String fileName) {
        if (fileName == null || "".equals(fileName)) {
            throw new RuntimeException("文件名不存在");
        }
        int position = fileName.lastIndexOf(".");
        if (position != -1) {
            return fileName.substring(position + 1, fileName.length());
        } else {
            throw new RuntimeException("文件名后缀不存在");
        }
    }

    public String createIntRandomString(int num) {
        if (num <= 4) {
            num = 4;
        }
        StringBuffer sb = new StringBuffer(10);
        Random random = new Random();
        for (int i = 0; i < num; i++) {
            int randomValue = random.nextInt(9);
            sb.append(randomValue);
        }
        return new String(sb);
    }

    /**
     * 文件重命名
     */
    public String getNewFileName(String fileName) {
        // 文件名后缀
        String filetype = getFiletype(fileName);
        String yyyyMMddhhmmsss;
        synchronized (SimpleCosFileRenamePolicy.class) {
            yyyyMMddhhmmsss = new SimpleDateFormat("yyyyMMddhhmmsss").format(new Date());
        }
        return yyyyMMddhhmmsss + createIntRandomString(4) + "." + filetype;
    }

    public File rename(File file) {
        file = new File(file.getParent(), getNewFileName(file.getName()));
        return file;
    }

}